package com.kgcx.order.rabbitmq;

import com.kgcx.common.client.schedule.pojo.ScheduleRecord;
import com.kgcx.common.eum.OrderEnum;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.order.domain.Order;
import com.kgcx.order.entity.OrderChangeMessage;
import com.kgcx.order.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * Created by zhulong on 17/11/13.
 * 派车失败
 */
@Component

public class AutoDispatchFailListener {

    private static final Logger LOG = LoggerFactory.getLogger(AutoDispatchFailListener.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderService service;

    @RabbitListener(queues = "kgcxOrderAutoDispatchFailQueue", concurrency = "1-10", errorHandler = "custRabbitListenerErrorHandler")
    public void processOrderStatus(String json) {

        LOG.info("订单 - 派车失败，json=" + json);
        System.out.println(json);
        //获取并解析消息
        ScheduleRecord scheduleRecord = JsonUtil.toObject(json, ScheduleRecord.class);

        //修改订单状态为派车失败
        stringRedisTemplate.opsForHash()
                .put(OrderEnum.ORDERS_STATUS, scheduleRecord.getOrder_no(),
                        String.valueOf(OrderEnum.AUTO_DISPATCH_FAIL));

        Object obj = stringRedisTemplate.opsForHash()
                .get(OrderEnum.ORDERS_ING, scheduleRecord.getOrder_no());
        if(obj != null && scheduleRecord != null)
        {
            System.out.println(obj.toString());
            Order order = JsonUtil.toObject(obj.toString(), Order.class);
            order.setOrderState(OrderEnum.AUTO_DISPATCH_FAIL);

            //订单入库
//            rabbitTemplate.convertAndSend(OrderEnum.ORDER_EXCHANGE,"kgcx.order.persistence", JsonUtil.toString(item));
            LOG.info("派车失败 - 调用取消订单持久化，json=" + json);
            service.cancelOrderPersistence(order);

            OrderChangeMessage mqMsg = new OrderChangeMessage(order.getOrderNo()
                    , OrderEnum.AUTO_DISPATCH_FAIL, OrderChangeMessage.MESSAGE_TYPE_DISPATCH_FAIL, "派车失败", order.getPlacingUserId());
            service.sendMqtt(JsonUtil.toString(mqMsg)
                    , OrderEnum.ORDER_STATE_TOPIC + "." + order.getPlacingUserId());
        }
    }
}
